"""
专利归宿分类处理
"""
import mysql.connector
from com.file import Item, exception
import uuid


class TransitionItem:
    @staticmethod
    def load_file(path):
        with open(path, "r") as f:
            return f.readlines()

    @staticmethod
    def write2mysql(items):
        con = mysql.connector.connect(user="root", password="123456", host="192.168.0.188", port="3306",
                                      database="patent")
        cursor = con.cursor()

        for item in items:
            assert item.item_id != ""
            assert item.patent_id != ""
            assert item.name != ""
            assert item.code != ""
            assert item.level != ""

            cursor.execute('insert into subject_item '
                           '(id, parent_id, title, subject_id, code, status, type, level) '
                           'values '
                           '(%s, %s, %s, %s, %s, %s, %s, %s )',
                           [item.item_id, item.patent_id, item.name, '', item.code, '-1', '1', item.level])

        con.commit()
        cursor.close()

    @staticmethod
    def wrapper_item(lines):
        result = []
        for line in lines:
            obj = line.strip().split(":")
            if obj.__len__() == 2:
                try:
                    code = obj[1].split("=")[1]
                    ele = Item.Item(uuid.uuid1().hex, "0", obj[0], int(code), 1)
                    result.append(ele)
                except IndexError as e:
                    print(e)
        return result

    @classmethod
    def process(cls, items):
        dict_item = {}
        for item in items:
            dict_item[item.code] = item.item_id

        for item in items:
            if 10 < item.code < 200:
                item.level = 2
                if 21 <= item.code <= 29:
                    item.patent_id = dict_item[2]
                elif 31 <= item.code <= 39:
                    item.patent_id = dict_item[3]
                elif 101 <= item.code <= 119:
                    item.patent_id = dict_item[1]
                else:
                    raise exception.UnSupportCodeException("未支持的code类型")
            elif 3201 <= item.code:
                item.level = 3
                if 3201 <= item.code <= 3299:
                    item.patent_id = dict_item[32]
                elif 3301 <= item.code <= 3399:
                    item.patent_id = dict_item[33]
                else:
                    raise exception.UnSupportCodeException("未支持的code类型")
        return items


if __name__ == '__main__':
    lines = TransitionItem.load_file("item.txt")
    items = TransitionItem.wrapper_item(lines)
    tmp = TransitionItem.process(items)
    TransitionItem.write2mysql(tmp)
